//
//  NSString+More.m
//  HCBTCSJ
//
//  Created by itte on 16/2/24.
//  Copyright © 2016年 itte. All rights reserved.
//

#import "NSString+More.h"

@implementation NSString (More)
//字符串判空
- (BOOL)isEmpty
{
    return !([self length] && [self stringByReplacingOccurrencesOfString:@" " withString:@""]);
}

// 是否全是数字
- (BOOL)isAllNumbers
{
    NSString *numRegex = @"^[0-9]\\d*$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numRegex];
    return [predicate evaluateWithObject:self];
}

// 是否为浮点数
- (BOOL)isPureFloat
{
    NSScanner *scan = [NSScanner scannerWithString:self];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

// 判断是否包含某子字符串
- (BOOL)isContainString:(NSString *)subString
{
    return [self rangeOfString:subString].location != NSNotFound;
}

//去掉空格和换行回车
- (NSString *)trimString
{
    if (self != nil)
    {
        return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }
    return @"";
}


// 生成MD5字符串
- (NSString *)md5FromString
{
    if ([self isEmpty]) {
        return @"";
    }
    const char *cStr = [[self trimString] UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr,(uint32_t)strlen(cStr),digest);
    
    NSString *s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",digest[0],  digest[1],
                   digest[2],  digest[3],
                   digest[4],  digest[5],
                   digest[6],  digest[7],
                   digest[8],  digest[9],
                   digest[10], digest[11],
                   digest[12], digest[13],
                   digest[14], digest[15]];
    return s;
}

// 字符串拼接在后面
- (NSString *)addString:(NSString *)subString
{
    return [NSString stringWithFormat:@"%@%@",self, subString];
}

//手机号码验证
- (BOOL)isMobilePhone
{
    NSString *phoneRegex = @"(^(01|1)[3,4,5,8][0-9])\\d{8}$" ;
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

//身份证号
- (BOOL)isIdentityCard
{
    if (self.length <= 0) {
        return NO;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:self];
}

// 打电话
- (void)callPhone
{
    if ([self isEmpty]) {
        return;
    }
    //去掉-
    NSString *phoneNumber = [self stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber.trimString]];
    UIAlertView *alertView = [UIAlertView bk_alertViewWithTitle:@"提示"
                                                        message:[NSString stringWithFormat:@"确定要拨打电话：%@？", phoneNumber]];
    [alertView bk_addButtonWithTitle:@"确定" handler:^{
        [[UIApplication sharedApplication] openURL:phoneURL];
    }];
    [alertView bk_setCancelButtonWithTitle:@"取消" handler:nil];
    [alertView show];
}
// 是否是Email
- (BOOL)isEmail
{
    NSString *emailRegex = @"^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

// 发邮件
- (void)sendEMail
{
    if ([self isEmpty] || ![self isEmail]) {
        return;
    }
    NSMutableString *mailUrl = [[NSMutableString alloc] init];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject:self];
    [mailUrl appendFormat:@"mailto:%@", [toRecipients componentsJoinedByString:@","]];
    //添加主题
//    [mailUrl appendString:@"&subject=联系我们"];
    NSString* email = [mailUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
}

// 所有数字个数
- (NSInteger)numbersCount
{
    if ([self.trimString isEmpty]) {
        return 0;
    }
    
    NSScanner *scanner = [NSScanner scannerWithString:self.trimString];
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    NSString *tempStr;
    NSInteger strNum = 0;
    while (![scanner isAtEnd]) {
        [scanner scanUpToCharactersFromSet:set intoString:NULL];
        [scanner scanCharactersFromSet:set intoString:&tempStr];
        strNum += tempStr.length;
        tempStr = @"";
    }
    return strNum;
}
// 将中文转换成英文
- (NSString *)transformToPinYin
{
    NSMutableString *pinyin = [self mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    return [pinyin uppercaseString];
}

// 判断是否为正确金额
- (BOOL)isValidMoney
{
    if ([self.trimString isEmpty]) {
        return NO;
    }
    BOOL ret = [self isPureFloat];
    if (!ret) {
        return NO;
    }
    NSString *firstChar = [self substringToIndex:1];
    if ([firstChar isEqualToString:@"."]) {
        return NO;
    }
    else if([firstChar  isEqualToString:@"0"]){
        if(self.length < 3){
            return NO;
        }
        NSString *secondeChar = [self substringWithRange:NSMakeRange(1, 1)];
        if (![secondeChar isEqualToString:@"."]) {
            return NO;
        }
    }
    if([self floatValue] < [@"0.01" floatValue]){
        return NO;
    }
    return YES;
}

// 获取字符串的宽度
- (CGFloat)widthOfStringWithFontSize:(CGFloat)fontsize andMaxHeight:(CGFloat)height
{
    CGSize size = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]} context:nil].size;
    return size.width;
}
// 获取字符串的高度
- (CGFloat)heightOfStringWithFontSize:(CGFloat)fontsize andMaxWidth:(CGFloat)width
{
    CGSize size = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]} context:nil].size;
    return size.height;
}
@end
